import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/event_bus.dart';
import 'package:yuan_hang_app/utils/permission_util.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/enter/model/main_model.dart';
import 'package:yuan_hang_app/views/home/home_page.dart';
import 'package:yuan_hang_app/views/mine/mine_page.dart';
import 'package:yuan_hang_app/views/msg/msg_page.dart';
import 'package:yuan_hang_app/views/report/report_page.dart';
import 'package:yuan_hang_app/widget/common_dialog.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

import '../../../res/w_colors.dart';

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _HomePageState();
}

class _HomePageState extends State<MainPage> {
  List _bodys = List.empty();
  late final PageController _pageController = PageController();
  String imTargetId = "";

  List tabItemList = [];
  int _currentPageIndex = 0;
  int unReadCount = 0;
  var bus = EventBus();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    tabItemList = MainModel().getTabList(WConstant().userInfo.companyId);
    _bodys = [
      const HomePage(),
      const ReportPage(),
      const MsgPage(),
      const MinePage()
    ];
    if (WConstant().userInfo.companyId == 1) {
      _bodys.removeAt(0);
    }

    PermissionUtil.requestPermission();
   if(Platform.isAndroid){
     PermissionUtil.requestNotifyPermission().then((permission) {
       if (permission != PermissionStatus.granted) {
         Toast.toast("请在系统设置中打开远航销售助手 APP的推送权限",duration: const Duration(seconds: 3));

       }
     });
   }
    bus.on("unReadCount", (arg) {
      unReadCount = arg;
      setState(() {});
    });
    getUnreadCount();
  }


  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      child: FullBasePage(
          hideNavi: true,
          bottomNavigationBar: Container(
            width: SizeUtils.screenW(),
            height: 48.px + MediaQuery.of(context).padding.bottom,
            padding: EdgeInsets.only(
                // left: 20.px,
                // right: 20.px,
                bottom: SizeUtils.bottomBar() > 10.px
                    ? SizeUtils.bottomBar() - 10.px
                    : 0),
            decoration: BoxDecoration(color: Colors.white, boxShadow: [
              BoxShadow(
                  color: WColors.CD5D5D5, //阴影颜色
                  blurRadius: 3.px),
            ]),
            child: ListView.builder(
              shrinkWrap: true,
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.zero,
              itemCount: tabItemList.length,
              itemBuilder: _barBuilder,
            ),
          ),
          child: PageView.builder(
            physics: const NeverScrollableScrollPhysics(),
            controller: _pageController,
            itemBuilder: (BuildContext context, int index) {
              return _bodys[index];
            },
            itemCount: _bodys.length,
          )),
      onPopInvoked: (didPop) {
        if (didPop) {
          return;
        }
        CommonDialog.showConformDialog(
            context: context,
            title: "提示",
            content: "你确认退出应用吗？",
            onConfirm: (text) {
              SystemNavigator.pop();
            });
      },
    );
  }

  Widget _barBuilder(context, index) {
    Map item = tabItemList[index];
    return GestureDetector(
      onTap: () {
        _currentPageIndex = index;
        _pageController.jumpToPage(index);
        setState(() {});
      },
      child: SizedBox(
        width: SizeUtils.screenW() / tabItemList.length,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Stack(
              children: <Widget>[
                Container(
                  width: 55.px,
                  padding: EdgeInsets.only(top: 2.px),
                  child: Image.asset(
                    index == _currentPageIndex
                        ? item["selected"]
                        : item["normal"],
                    width: 22.px,
                    height: 22.px,
                  ),
                ),
                Positioned(
                  top: 0,
                  right: unReadCount < 99 ? 15.px : 0,
                  child: Offstage(
                      offstage: !(unReadCount > 0 && item["title"] == "消息"),
                      child: Container(
                        height: 12.px,
                        width: unReadCount > 99 ? 24.px : 12.px,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: WColors.redMain,
                            borderRadius: BorderRadius.circular(12.px)),
                        child: WText(
                          unReadCount > 99 ? "99+" : unReadCount.toString(),
                          style:
                              TextStyle(color: WColors.white, fontSize: 9.px),
                        ),
                      )),
                )
              ],
            ),
            WText(item["title"],
                style: TextStyle(
                    color: index == _currentPageIndex
                        ? WColors.primaryColor
                        : WColors.hintTextColor,
                    fontSize: 10.px,
                    height: 1.6,
                    fontWeight: FontWeight.w500))
          ],
        ),
      ),
    );
  }

  void getUnreadCount() {
    HttpUtils()
        .get(
            "${Api.getNoticeMessageCount}?userId=${WConstant().userInfo.userId}")
        .then((value) {
      if (value.resultCode == 200 && value.data["resultCode"] == 200) {
        var msgCount = value.data["data"];
        int count1 = msgCount?['notNum'] ?? 0;
        int count2 = msgCount?['taskNum'] ?? 0;
        unReadCount = count2 + count1;
        setState(() {});
      } else {
        Toast.toast(value.errMsg ?? "");
      }
    }).catchError((e) {});
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    bus.off("unReadCount");
  }
}
